﻿/*********************************************************
 * 开发人员：小兵
 * 创建时间：2012-10-22 14:32:35
 * 描述说明：
 * 
 * 更改历史：
 * 
 * *******************************************************/
namespace Mozlite.Components
{
    using System;
    using System.Web;
    using System.Data;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    /// <summary>
    /// 路由管理类。
    /// </summary>
    public static class Routes
    {
        private const string routeCacheKey = "AllRoutes";
        /// <summary>
        /// 添加或更新网站路由实例对象。
        /// </summary>
        /// <param name="route">路由实例对象。</param>
        /// <returns>返回更新结果。</returns>
        public static bool Save(this Route route)
        {
            if(string.IsNullOrEmpty(route.AreaName))
                route.AreaName = NullArea;
            bool saved = false;
            if(route.RouteID > 0)
                saved = Database.ExecuteNonQuery("UPDATE moz_SiteUrls SET AreaName = @AreaName, [Key] = @Key, Url = @Url, RouteHandlerType = @RouteHandlerType, Defaults = @Defaults, Constraints = @Constraints, Namespaces = @Namespaces WHERE RouteID = @RouteID;", new
                {
                    AreaName = route.AreaName,
                    Key = route.Key,
                    Url = route.Url,
                    RouteHandlerType = route.RouteHandlerType,
                    Defaults = route.Defaults,
                    Constraints = route.Constraints,
                    Namespaces = route.Namespaces,
                    RouteID = route.RouteID
                });
            else
                saved = Database.ExecuteNonQuery("INSERT INTO moz_SiteUrls(AreaName,[Key],Url,RouteHandlerType,Defaults,Constraints,Namespaces)VALUES(@AreaName,@Key,@Url,@RouteHandlerType,@Defaults,@Constraints,@Namespaces);", new
                {
                    AreaName = route.AreaName,
                    Key = route.Key,
                    Url = route.Url,
                    RouteHandlerType = route.RouteHandlerType,
                    Defaults = route.Defaults,
                    Constraints = route.Constraints,
                    Namespaces = route.Namespaces
                });
            if(saved)
                Caches.Remove(routeCacheKey);
            return saved;
        }

        /// <summary>
        /// 空区域名称。
        /// </summary>
        public const string NullArea = "NullArea";

        /// <summary>
        /// 获取网站路由实例对象。
        /// </summary>
        /// <param name="routeID">路由ID。</param>
        /// <returns>返回网站路由实例对象。</returns>
        public static Route GetRoute(int routeID)
        {
            return Database.ExecuteReader<Route>("SELECT * FROM moz_SiteUrls WHERE RouteID = " + routeID);
        }

        /// <summary>
        /// 删除网站路由。
        /// </summary>
        /// <param name="routeIDs">网站路由ID集合，以“,”分割。</param>
        /// <returns>返回删除结果。</returns>
        public static bool Delete(string routeIDs)
        {
            if(Database.ExecuteNonQuery("DELETE FROM moz_SiteUrls WHERE RouteID{0}".FormatWith(routeIDs.FormatIDs())))
            {
                Caches.Remove(routeCacheKey);
                return true;
            }
            return false;
        }

        /// <summary>
        /// 载入网站路由列表。
        /// 第一主键：区域字符串。
        /// 第二主键：路由名称字符串。
        /// </summary>
        /// <returns>返回网站路由列表。</returns>
        public static Dictionary<string, Dictionary<string, Route>> LoadRoutes()
        {
            return Caches.Get<Dictionary<string, Dictionary<string, Route>>>(routeCacheKey, Consts.MinuteSeconds * 3, Consts.MinuteSeconds * 3, () =>
            {
                var routes = new Dictionary<string, Dictionary<string, Route>>(StringComparer.OrdinalIgnoreCase);
                using(var reader = Database.ExecuteReader("SELECT * FROM moz_SiteUrls")) {
                    while(reader.Read()) {
                        var route = reader.As<Route>();
                        if(!routes.ContainsKey(route.AreaName))
                            routes.Add(route.AreaName, new Dictionary<string, Route>(StringComparer.OrdinalIgnoreCase));
                        routes[route.AreaName].Add(route.Key, route);
                    }
                    reader.Close();
                }
                return routes;
            });
        }

        /// <summary>
        /// 获取Key和Id指示的URL地址。
        /// </summary>
        /// <param name="urlFormat">URL地址，如果是路由键，使用“{key}”格式。</param>
        /// <param name="keys">路由键实例对象。</param>
        /// <param name="areaName">区域名称。</param>
        /// <returns>返回URL地址。</returns>
        public static string GetFormattedUrl(string urlFormat, IDictionary<string, object> keys, string areaName = null)
        {
            if (urlFormat == null || urlFormat.IsUrl())
                return urlFormat;
            if (urlFormat.IndexOf("~/") == -1)
            {
                urlFormat = SiteUrls.FormatUrl(urlFormat, keys, areaName);
                return urlFormat;
            }
            return Cores.GetUrl(urlFormat);
        }
    }
}
